<template>
    <div class="buy-detail">
        <div v-show="!pageLoading">
            <div class="back-btn" @click="$router.back(-1)">
                <van-icon name="arrow-left" style="color:#fff;"/>
            </div>
            <!--<div class="more-btn" @click="showReportBtn = !showReportBtn">-->
            <!--<img src="../static/img/images/more.png" alt="">-->
            <!--</div>-->
            <!--<div class="report-btn" v-if="showReportBtn">-->
            <!--&lt;!&ndash;<div @click="Share()">Share(testing)</div>&ndash;&gt;-->
            <!--<div @click="goToReport()">Report problem</div>-->
            <!--</div>-->
            <van-swipe v-if="images.length &gt; 0" :loop="false">
                <van-swipe-item v-for="(image, index) in images" :key="index">
                    <div class="banner-box">
                        <!--<img :src="image.url" :style="defaultImage" preview="0" class="swiper-banner" alt=""/>-->
                        <!--<img :src="image.url" preview="0" class="swiper-banner shopgogo" alt=""/>--><!--图片预览-->
                        <img v-lazy="image.url" :key="image.url" class="swiper-banner shopgogo" alt=""/>
                    </div>

                </van-swipe-item>
            </van-swipe>
            <!--<div class="swiper-banner no-image" v-else>-->
            <!--<div>ShopGoGo</div>-->
            <!--</div>-->
            <div class="container-box">
                <div class="title" v-if="title">{{translateString(title)}}</div>
                <van-row style="line-height: 1.5;">
                <span>
                     <van-col span="12" class="price" v-if="priceType == 2"><span class="ft-14">Lks&nbsp;</span>{{regexNum(price)}}</van-col>
                     <van-col span="12" class="price" v-else-if="priceType == 1"><span class="ft-14">Ks&nbsp;</span>{{regexNum(price)}}</van-col>
                     <van-col span="12" class="price" v-else><span
                         class="ft-14">USD </span>{{regexNum(price)}}</van-col>
                </span>
                    <van-col span="12" class="date-time ft-14 margin-b" v-if="createDatetime">
                        {{getDateDiff(createDatetime)}}
                    </van-col>
                </van-row>
                <div class="detail-items margin-b" v-if="condition != null">
                    <div class="item-title">{{$t('m.Condition')}}</div>
                    <p class="item-info ft-14">{{getCondition(condition)}}</p>
                </div>
                <!--<div class="detail-items margin-b" v-if="brand">-->
                <!--<div class="item-title">Brand</div>-->
                <!--<p class="item-info ft-14" style="color:#0E6C9C;" @click="goToSearch(brand)">{{brand}}</p>-->
                <!--</div>-->
                <div class="detail-items margin-b" v-if="category.length > 0">
                    <div class="item-title">{{$t('m.Category')}}</div>
                    <p class="item-info ft-14">
                        <span v-for="(item, index) in category" class="item-info-categroy" @click="goToSearch(item)">{{getCategoryText(item)}}</span>
                    </p>
                </div>
                <div class="detail-items margin-b" v-for="(item, index) in properties" v-if="item.text">
                    <div class="item-title">{{getPropertiesInfo(item, categoryId, 0)}}</div>
                    <p class="item-info ft-14" v-if="item.propertyId == 51 && item.valueId == 480 "
                       style="color:#0E6C9C;" @click="goToSearch(item)">{{translateString(item.text)}}</p><!--Brand-->
                    <p class="item-info ft-14" v-else>{{getPropertiesInfo(item, categoryId, 1)}}</p>
                    <!--<p class="item-info ft-14" v-else>{{item.text}}</p>-->
                </div>
                <div class="detail-items margin-b" v-for="item in phoneProperty" v-if="phoneProperty.length>0">
                    <div class="item-title">{{item.label}}</div>
                    <p class="item-info ft-14">{{item.text}}</p>
                </div>

                <div class="detail-items margin-b" v-if="viewPhone">
                    <div class="item-title">Specification</div>
                    <p class="item-info">
                        <van-button
                            @click="$router.push({path:'/compare-phone/phone-detail', query: {propertyValueId: viewPhone}})"
                            size="small" type="default" style="">View
                        </van-button>
                    </p>
                </div>

                <div class="margin-b" v-show="description"><!--此处不可用v-if 避免下方ref取不到-->
                    <div class="item-title">{{$t('m.Description')}}</div>
                    <p class="item-info ft-14 description" :class="fold ? 'fold' : 'unfold'" ref="description"
                       v-html="translateString(description)"></p>
                    <div class="more-description" v-show="fold" @click="fold = !fold">More</div>
                </div>
                <!--<div class="detail-items margin-b" v-if="adId">-->
                <!--<div class="item-title">Ad ID</div>-->
                <!--<p class="item-info ft-14">{{adId}}</p>-->
                <!--</div>-->
            </div>
            <div class="cap-title" v-if="regionId || townshipId">{{$t('m.Location')}}</div>
            <div class="location" v-if="regionId || townshipId">{{getRegionType(regionId)}} -
                {{getTownshipType(townshipId)}}
            </div>
            <div class="cap-title" v-if="sellerInfo.photo || sellerInfo.name">{{$t('m.Seller')}}</div>
            <div class="user-info-box" v-if="sellerInfo.photo || sellerInfo.name">
                <span class="user-info" @click="goToSellerDetail(sellerInfo.id)">
                    <i class="i-icon1">
                        <img :src="sellerInfo.photo" :onerror="defaultHeadImg"/>
                    </i>
                    <p class="title">{{translateString(sellerInfo.name)}}</p>
                    <van-row class="face-icon-box confirmed" v-if="sellerInfo.facebook_id || sellerInfo.phoneFlag">
                        <van-col class="confirmed-title" style="margin-right: 10px;">{{$t('m.Confirmed')}}</van-col>
                        <van-col>
                            <span class="bindphone" style="margin-right: 5px" v-if="sellerInfo.phoneFlag">
                                <img src="../static/img/images/bindphone.png"/>
                            </span>
                            <span class="bindfacebook" style="margin-right: 5px" v-if="sellerInfo.facebook_id">
                                <img src="../static/img/images/bindfacebook.png"/>
                            </span>
                        </van-col>
                    </van-row>
                    <!--<van-row class="face-icon-box">-->
                    <!--<van-col span="8">{{sellerInfo.rating}}</van-col>-->
                    <!--<van-col span="16">-->
                    <!--<span class="face-icon">-->
                    <!--<img src="../static/img/images/meh.png" />-->
                    <!--18-->
                    <!--</span>-->
                    <!--<span class="face-icon">-->
                    <!--<img src="../static/img/images/smile.png" />-->
                    <!--18-->
                    <!--</span>-->
                    <!--<span class="face-icon">-->
                    <!--<img src="../static/img/images/frown.png" />-->
                    <!--18-->
                    <!--</span>-->
                    <!--</van-col>-->
                    <!--</van-row>-->
                </span>
            </div>
            <div class="report-problem">
                <van-cell-group>
                    <van-cell :title="'Ad ID: ' + adIdShopgogo">
                        <template slot="">
                            <span class="van-cell-text" @click="goToReport()">{{$t('m.ReportAd')}}</span>
                        </template>
                    </van-cell>
                </van-cell-group>
            </div>

            <div class="cap-title" v-if="tableData.length > 0">{{$t('m.Youmayalsolike')}}</div>
            <van-list
                v-model="loading"
                :finished="finished"
                loading-text=" "
                @load="getList"
                class="main-explore">
                <div class="explore-item" @click="goToDetail(item.id)" v-for="(item, index) in tableData" :key="index"
                     v-bind:class="[tableData.length % 2 == 0 ? twoClass : oneClass]">
                    <!--<div class="explore-item-icon">-->
                    <!--&lt;!&ndash;<img :src="item.image"  v-lazy="item.image">&ndash;&gt;-->
                    <!--<img v-lazy="item.cover"  :style="defaultImage" alt="" />-->
                    <!--</div>-->
                    <div class="explore-item-icon">
                        <!--<img :src="item.cover" :style="defaultImage" alt=""/>-->
                        <img v-lazy="item.cover" alt="" :key="item.cover" :onload="getWidthAndHeight(item, index)"
                             :class="[item.wth == 1 ? 'width-max' : 'height-max']"/>
                    </div>
                    <div class="explore-item-label">{{translateString(item.title)}}</div>
                    <span>
                        <div class="explore-item-label price" v-if="item.priceType == 2">Lks&nbsp;{{regexNum(item.price)}}</div>
                        <div class="explore-item-label price" v-else>Ks&nbsp;{{regexNum(item.price)}}</div>
                    </span>
                    <!--<div class="explore-item-label dates">{{getDateDiff(item.createDatetime)}}</div>-->
                </div>
            </van-list>
            <div style="height: 50px;"></div>
            <div class="edit-btn-box" v-if="userId !== null && sellerId !== null && userId == sellerId">
                <van-button size="large" class="edit-btn" :loading="btnLoading" @click="goToEdit()">Edit</van-button>
            </div>
            <van-goods-action v-else>
                <van-cell-group class="save">
                    <van-cell :title="$t('m.Save')" icon="like-o" @click="onClickSave" class="save-btn" v-if="!saved"/>
                    <van-cell :title="$t('m.Save')" icon="like" @click="onClickSave" class="save-btn saved" v-else/>
                </van-cell-group>
                <van-goods-action-big-btn v-if="!sellerInfo.facebook_messenger_url" :text="$t('m.Chat')"
                                          class="chat-btn" @click="onChat"/>
                <van-goods-action-big-btn v-if="sellerInfo.facebook_messenger_url" text="Facebook" class="chat-btn"
                                          @click="onToFacebookMessage(sellerInfo.facebook_messenger_url)"/>

                <van-goods-action-big-btn :text="$t('m.Call')" v-if="sellerInfo.phoneFlag && sellerInfo.phone"
                                          @click="onClickCallBtn(sellerInfo.phone)" class="buy-btn"/>
                <van-goods-action-big-btn :text="$t('m.Buy')" v-else @click="onChat" class="buy-btn"/>
            </van-goods-action>
        </div>
        <van-loading v-show="pageLoading" color="black" class="loading-page"/>
    </div>
</template>
<script>
    import Qs from 'qs'
    import {buyInformation, searchBuyList, submitSave, getUserInfo, getDetailCount} from '../static/api/mgc_api'
    import {chatAppkey, getModelJson} from '../static/api/zxy_api';
    import {ImagePreview} from 'vant';

    // 英文翻译
    import township from '../static/json/township'
    import region from '../static/json/region'
    import categoryJson from '../static/json/category'
    // 缅文
    import mm_region from '../static/mmJson/region'
    import mm_township from '../static/mmJson/township'
    import mm_categoryJson from '../static/mmJson/category'
    // 缅文Unicode
    import mmu_region from '../static/mmUnicodeJson/region'
    import mmu_township from '../static/mmUnicodeJson/township'
    import mmu_categoryJson from '../static/mmUnicodeJson/category'
    import phoneBrand from '../static/json/phoneBrand'

    export default {
        name: 'BuyDetail',
        data() {
            return {
                phoneBrand: phoneBrand,
                defaultHeadImg: 'this.src="' + require('../static/img/images/user-head.png') + '"',
                defaultImage: {
                    backgroundImage: "url(" + require("../static/img/images/default-list.png") + ")",
                    backgroundRepeat: "no-repeat",
                    backgroundSize: "100% 100%",
                },
                oneClass: 'one',
                twoClass: 'two',
                btnLoading: false,
                userId: null,
                sellerId: null,
                saved: false,
                pageLoading: false,
                loading: false,
                finished: true,
                tableData: [],
                pageData: {
                    pageNum: 1,
                    pageSize: 10,
                },
                pageInfo: {
                    totalCount: 0,
                    totalPages: 0
                },
                images: [],
                showReportBtn: false,
                fold: false,
                title: '',
                price: null,
                priceType: null,
                createDatetime: null,
                condition: null,
                brand: '',
                category: [],
                series: '',
                storage: '',
                description: '',
                adId: '',
                adIdShopgogo: '',
                id: '',
                regionId: null,
                townshipId: null,
                categoryId: null,
                properties: [],
                sellerInfo: {
                    name: '',
                    id: '',
                    easemob_account: '',
                    photo: '',
                    rating: 'rating',
                    phone: '',
                    facebook_id: '',
                    phoneFlag: '',
                    facebook_messenger_url: ''
                },
                myItems: '',
                phoneProperty: [],
                viewPhone: null
            };
        },
        computed: {
            townshipJson() {
                if (this.$store.state.store.localLang == 'MM') {
                    return mm_township
                } else if (this.$store.state.store.localLang == 'MMU') {
                    return mmu_township
                } else {
                    return township
                }
            },
            regionJson() {
                if (this.$store.state.store.localLang == 'MM') {
                    return mm_region
                } else if (this.$store.state.store.localLang == 'MMU') {
                    return mmu_region
                } else {
                    return region
                }
            },
            categoryJson() {
                if (this.$store.state.store.localLang == 'MM') {
                    return mm_categoryJson
                } else if (this.$store.state.store.localLang == 'MMU') {
                    return mmu_categoryJson
                } else {
                    return categoryJson
                }
            },
            conditions() {
                if (this.$store.state.store.localLang == 'MM') {
                    return [
                        {text: 'အသစ္', value: 0},
                        {text: 'အသံုးျပဳျပီးသား', value: 1},
                    ]
                } else if (this.$store.state.store.localLang == 'MMU') {
                    return [
                        {text: 'အသစ်', value: 0},
                        {text: 'အသုံးပြုပြီးသား', value: 1},
                    ]
                } else {
                    return [
                        {text: 'New', value: 0},
                        {text: 'Used', value: 1},
                    ]
                }
            },
        },
        methods: {
            onChat() {

                // 应用是否登录
                if (!this.$store.state.store.isLogin) {
                    this.$router.push('/login-register/loginregister')
                    return;
                }

                // 聊天系统系统登录
                if (!this.$store.state.store.chatLoginStatus) {
                    this.$toast({
                        mask: true,
                        forbidClick: true,
                        message: 'Loading...Please wait'
                    });
                }

                if (this.$store.state.store.chatLoginStatus) {

                    // 发起一个聊天
                    if (!$applozic) {
                        this.$toast('The chat plugin is missing, please return to the home page to refresh')
                        this.$router.push('/login-register/loginregister')
                        console.log('插件js没有下载')
                        return '聊天插件没有实例化';
                    }

                    // 获取本地存储中的数据
                    let userInfo = localStorage.getItem("userInfo") || '';
                    if (userInfo) {
                        userInfo = JSON.parse(userInfo) || '';
                    } else {
                        this.$router.push('/login-register/loginregister')
                        console.log('用户没有登录');
                        return;
                    }

                    let groupData = {
                        clientGroupId: this.id + ',' + userInfo.id,  // optional
                        groupName: this.translateString(this.title) || '',
                        groupMemberList: [userInfo.id, this.sellerInfo.id],
                        imageUrl: this.images[0].url || 'https://firebasestorage.googleapis.com/v0/b/klets-3642/o/user_files%2FHku1c4Pt%2F47edad6a000a40d19f369fc6cc683b57%2Fin-arlington-virginia-a-drafty-house-was-made-more-than-twice-as-efficient-with-the-addition-of-metal-both-inside-and-out-roof-panels-topping-the-brick-envelope-echo-its-original-geometry.jpg?alt=media&token=bea34579-566c-4cfb-8186-05b2c45273e2',
                    }

                    // 发起创建组请求前,用toast阻止重复点击
                    this.$toast({
                        mask: true,
                        forbidClick: true,
                        message: 'loading...'
                    });
                    $.ajax({
                        url: "https://apps.applozic.com/rest/ws/group/v2/create",
                        type: 'POST',
                        dataType: 'json',
                        data: JSON.stringify(groupData),
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("Application-Key", `${chatAppkey}`);
                            xhr.setRequestHeader("Authorization", localStorage.getItem('Authorization'));
                            xhr.setRequestHeader("Device-Key", localStorage.getItem('Device-Key'));
                        },
                        contentType: 'application/json',
                        success: (res) => {

                            // 清除toast
                            this.$toast.clear();

                            if (res.status == 'success') {
                                let groupId = res.response.id;
                                console.log('创建组成功', groupId, '---groupId', this.id + ',' + userInfo.id, '---topicId')
                                // $applozic.fn.applozic('loadContextualTab', ({
                                //     // 'clientGroupId': this.id + userInfo.id
                                //     'groupId': groupId, // GroupId whom you want to add in topic based chat
                                //     'topicId': this.id + '' + userInfo.id + 'topic', // 图片id和用户id Unique identifier for product/Topic
                                //     "topicDetail": {
                                //         title: this.translateString(this.title) || '', // Product Title
                                //         subtitle: "", //Product Sub-title
                                //         link: this.images[0].url || 'https://firebasestorage.googleapis.com/v0/b/klets-3642/o/user_files%2FHku1c4Pt%2F47edad6a000a40d19f369fc6cc683b57%2Fin-arlington-virginia-a-drafty-house-was-made-more-than-twice-as-efficient-with-the-addition-of-metal-both-inside-and-out-roof-panels-topping-the-brick-envelope-echo-its-original-geometry.jpg?alt=media&token=bea34579-566c-4cfb-8186-05b2c45273e2', //Product Image Link
                                //         key1: this.priceType == 2 ? "Lks" : "Ks", //Small text anything Like qty(Optional)
                                //         value1: this.price || '', //Value of key 1
                                //         key2: 'ID',        // Small text anything like MRP (product price) (Optional).
                                //         value2: this.id || ''   // Value of key2 ex-$100(Optional)
                                //     },
                                //     'isGroup': true,
                                //     'status': "new"
                                // }));

                                // 清空session中的数据
                                window.ALStorage.clearMckMessageArray();

                                window.$applozic.fn.applozic('loadGroupTabByClientGroupId', {'clientGroupId': this.id + ',' + userInfo.id});

                                // 清空session 使得主动去拉联系人列表,做了延时处理，最大限度保障异步执行完成之后执行清空数组的操作
                                // setTimeout(()=>{
                                //     sessionStorage.setItem('mckLatestMessageArray', JSON.stringify([]))
                                // },500)

                                this.$store.commit('store/updateSubjectDetail', {
                                    show: true,
                                    imgUrl: this.images[0].url,
                                    title: this.translateString(this.title),
                                    priceType: this.priceType,
                                    price: this.price,
                                    goodsId: this.id
                                })

                            } else if (res.status == 'error') {
                                if (res.errorResponse && res.errorResponse[0].description === "group already exists") {
                                    console.log('已经存在组，创建组失败回调，当前clientGroupId', this.id + ',' + userInfo.id, '根据clientGroupId查询groupId')

                                    // 清空session中的数据
                                    window.ALStorage.clearMckMessageArray();

                                    window.$applozic.fn.applozic('loadGroupTabByClientGroupId', {'clientGroupId': this.id + ',' + userInfo.id});

                                    this.$store.commit('store/updateSubjectDetail', {
                                        show: true,
                                        imgUrl: this.images[0].url,
                                        title: this.translateString(this.title),
                                        priceType: this.priceType,
                                        price: this.price,
                                        goodsId: this.id
                                    })
                                }
                            }

                        }
                    });
                }

            },
            onToFacebookMessage(link) {
                location.href = link;
            },
            regexNum(v, len, split) {
                split = split || ',', len = Math.abs((+len) % 20 || 2)
                v = parseFloat((v + '').replace(/[^\d\.-]/g, '')).toFixed(len) + ''
                v = parseFloat(v) + ''
                return v.replace(/\d+/, function (v) {
                        var lit = v.length % 3 == 0
                        var index = lit ? v.length - 3 : -1
                        return v.split('').reverse().join('').replace(/\d{3}/g, function (k, l) {
                            return k + ((l == index && lit) ? '' : split)
                        }).split('').reverse().join('')
                    }
                )
            },
            translateString(str) {
                if (!str) return ''
                return this.$translateLang(str, 'unicodeTozawgyi');
            },
            getDateDiff(dateTimeStamp) {
                if (!dateTimeStamp) return
                let minute = 1000 * 60
                let hour = minute * 60
                let day = hour * 24
                let month = day * 30
                let year = day * 365
                let now = new Date().getTime()
                let diffValue = now - dateTimeStamp
                if (diffValue < 0) return
                let monthC = diffValue / month
                let yearC = diffValue / year
                let weekC = diffValue / (7 * day)
                let dayC = diffValue / day
                let hourC = diffValue / hour
                let minC = diffValue / minute
                let result = ''

                if (yearC >= 1) {
                    if (parseInt(yearC) > 1) {
                        result = "" + parseInt(yearC) + " years ago"
                    } else {
                        result = "" + parseInt(yearC) + " year ago"
                    }
                } else if (monthC >= 1) {
                    if (parseInt(monthC) > 1) {
                        result = "" + parseInt(monthC) + " months ago"
                    } else {
                        result = "" + parseInt(monthC) + " month ago"
                    }
                } else if (weekC >= 1) {
                    if (parseInt(weekC) > 1) {
                        result = "" + parseInt(weekC) + " weeks ago"
                    } else {
                        result = "" + parseInt(weekC) + " week ago"
                    }
                } else if (dayC >= 1) {
                    if (parseInt(dayC) > 1) {
                        result = "" + parseInt(dayC) + " days ago"
                    } else {
                        result = "" + parseInt(dayC) + " day ago"
                    }
                } else if (hourC >= 1) {
                    if (parseInt(hourC) > 1) {
                        result = "" + parseInt(hourC) + " hours ago"
                    } else {
                        result = "" + parseInt(hourC) + " hour ago"
                    }
                } else if (minC >= 1) {
                    if (parseInt(minC) > 1) {
                        result = "" + parseInt(minC) + " minutes ago"
                    } else {
                        result = "" + parseInt(minC) + " minute ago"
                    }
                }
                return result;
            },
            goToSearch(val) {
                if (val.propertyId == 51 && val.valueId == 480) {
                    this.$router.push({
                        path: '/buy-list',
                        query: {
                            brand: val.text
                        }
                    })
                } else {
                    let txt = this.getCategoryText(val)
                    this.$router.push({
                        path: '/buy-list',
                        query: {
                            categoryId: val.id,
                            category: txt
                        }
                    })
                }

            },
            goToSellerDetail(id) {
                this.$router.push({
                    path: '/user/other-account',
                    query: {
                        userId: id
                    }
                })
            },
            getDetail(id) {
                this.pageLoading = true
                buyInformation(id).then((res) => {
                    if (res.data.errorID === 0) {
                        if (res.data.object) {
                            let obj = res.data.object

                            this.images = obj.images.sort((a, b) => a.sequence - b.sequence)
                            this.title = obj.title
                            this.price = obj.price
                            this.priceType = obj.priceType
                            this.createDatetime = obj.createDatetime
                            this.condition = obj.condition
                            this.brand = obj.brand
                            this.category = []
                            if (obj.category) {
                                let _c = obj.category.categoryName.split('/');
                                let _d = obj.category.id.split('/');
                                if (_c.length > 0) {
                                    for (let i = 0; i < _c.length; i++) {
                                        let _o = {
                                            text: '',
                                            id: ''
                                        }
                                        _o.text = _c[i];
                                        _o.id = _d[i];
                                        this.category.push(_o)
                                    }
                                }
                            }
                            this.categoryId = obj.categoryId
                            this.properties = obj.values

                            if (typeof(obj.values) == 'object' && obj.values.length > 0) {
                                let modelValueId;
                                for (let i = 0; i < obj.values.length; i++) {
                                    if (obj.values[i].propertyId == '8') {
                                        modelValueId = obj.values[i].valueId;
                                        for (let j = 0; j < this.phoneBrand.properties.values.length; j++) {
                                            if (this.phoneBrand.properties.values[j].id == obj.values[i].valueId) {
                                                this.phoneProperty.push({
                                                    id: this.phoneBrand.properties.values[j].id,
                                                    label: 'Mobile Brand',
                                                    text: this.phoneBrand.properties.values[j].text,
                                                })
                                                break;
                                            }
                                        }
                                    }
                                    if (obj.values[i].propertyId == '57') {
                                        let modelValue = [];

                                        // 请求model数据
                                        getModelJson(modelValueId).then((res) => {
                                            modelValue = res.data.object;

                                            // modelValue = this.brandForModel.values[modelValueId]

                                            for (let k = 0; k < modelValue.length; k++) {
                                                if (modelValue[k].id == obj.values[i].valueId) {
                                                    this.phoneProperty.push({
                                                        id: modelValue[k].id,
                                                        label: 'Mobile Model',
                                                        text: modelValue[k].text,
                                                    })
                                                    this.viewPhone = modelValue[k].id;  // 传入modle id
                                                    break;
                                                }
                                            }

                                        }).catch((e) => {
                                            console.log(e)
                                        })


                                    }
                                }
                            }

                            if (obj.desc) {
                                this.description = obj.desc.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(new RegExp("\n", "gm"), '<br/>')
                                setTimeout(() => {
                                    if (this.$refs.description) {
                                        // console.log(this.$refs.description.offsetHeight)
                                        if (this.$refs.description.offsetHeight >= 88) {
                                            // description每行高度22,高度少于四行时不显示More
                                            this.fold = true
                                        }
                                    }
                                }, 200)
                            }
                            this.adId = obj.id
                            this.adIdShopgogo = obj.adIdShopgogo
                            this.regionId = obj.regionId
                            this.townshipId = obj.townshipId

                            this.sellerInfo.id = obj.sellerInfo.id || ''
                            this.sellerInfo.name = obj.sellerInfo.name || ''
                            this.sellerInfo.easemob_account = obj.sellerInfo.easemob_account || ''
                            this.sellerInfo.photo = obj.sellerInfo.photo || ''
                            this.sellerId = obj.sellerInfo.id || ''
                            this.sellerInfo.phone = obj.sellerInfo.account || ''
                            this.sellerInfo.phoneFlag = obj.sellerInfo.phoneFlag || ''
                            this.sellerInfo.facebook_id = obj.sellerInfo.facebook_id || ''
                            this.sellerInfo.facebook_messenger_url = obj.sellerInfo.facebook_messenger_url || ''
                            if (obj.favorStatus && obj.favorStatus == 1) {
                                this.saved = true
                            } else {
                                this.saved = false
                            }
                            // 不是从my-items进入的detail才加载底部列表
                            if (!this.myItems) {
                                this.finished = false
                            }
                            this.pageLoading = false
                        }
                    } else {
                        this.$toast(res.data.message)
                        this.finished = false
                        this.pageLoading = false
                    }
                }).catch((e) => {
                    console.log(e)
                    this.$toast('No internet, please try again')
                })
            },
            getDetailCount(id) {
                let data = {
                    'id': id,
                    'source': 'web'
                }
                let params = Qs.stringify(data)
                getDetailCount(params).then((res) => {
                    if (res.data.errorID != 0) {
                        console.log(res.data.message)
                    }
                }).catch((e) => {
                    console.log(e)
                })
            },
            // showImage(index) {
            //     console.log(index,'index')
            //     let arr = this.images
            //     let imageArr = []
            //     if (arr.length > 0) {
            //         for (let i=0; i<arr.length; i++) {
            //             let i_url = arr[i].url
            //             imageArr.push(i_url)
            //         }
            //         ImagePreview(imageArr, index);
            //     }
            //     console.log(imageArr,'imageArr')
            // },
            getCategoryText(item) {
                let obj = this.categoryJson

                for (let i = 0; i < obj.length; i++) {
                    if (item.id == obj[i].id) {
                        return obj[i].name
                    } else {
                        if (obj[i].children) {
                            for (let j = 0; j < obj[i].children.length; j++) {
                                if (item.id == obj[i].children[j].id) {
                                    return obj[i].children[j].name
                                } else {
                                    if (obj[i].children[j].children) {
                                        for (let k = 0; k < obj[i].children[j].children.length; k++) {
                                            if (item.id == obj[i].children[j].children[k].id) {
                                                return obj[i].children[j].children[k].name
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            },
            getPropertiesInfo(item, id, type) {
                // if (!item) return false;
                // type --  0: title; 1: text
                for (let i = 0; i < this.categoryJson.length; i++) {
                    if ((id == this.categoryJson[i].id) && this.categoryJson[i].properties) {
                        let pros = this.categoryJson[i].properties
                        for (let t = 0; t < pros.length; t++) {
                            for (let g = 0; g < pros[t].values.length; g++) {
                                if (item.valueId == pros[t].values[g].id) {
                                    if (type == 0) {
                                        return pros[t].name
                                    } else {
                                        //  pros[t].values.length == 1时是输入框输入的内容，category中的pros[t].values[g].text == Others,此时要返回输入的内容item.text
                                        if (pros[t].values.length > 1) {
                                            return pros[t].values[g].text
                                        } else {
                                            return item.text
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        if (this.categoryJson[i].children.length > 0) {
                            for (let j = 0; j < this.categoryJson[i].children.length; j++) {
                                if ((id == this.categoryJson[i].children[j].id) && this.categoryJson[i].children[j].properties) {
                                    let pros = this.categoryJson[i].children[j].properties
                                    for (let t = 0; t < pros.length; t++) {
                                        for (let g = 0; g < pros[t].values.length; g++) {
                                            if (item.valueId == pros[t].values[g].id) {
                                                if (type == 0) {
                                                    return pros[t].name
                                                } else {
                                                    if (pros[t].values.length > 1) {
                                                        return pros[t].values[g].text
                                                    } else {
                                                        return item.text
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    if (this.categoryJson[i].children[j].children.length > 0) {
                                        for (let k = 0; k < this.categoryJson[i].children[j].children.length; k++) {
                                            if ((id == this.categoryJson[i].children[j].children[k].id) && this.categoryJson[i].children[j].children[k].properties) {
                                                // console.log(123)
                                                let pros = this.categoryJson[i].children[j].children[k].properties
                                                for (let t = 0; t < pros.length; t++) {
                                                    for (let g = 0; g < pros[t].values.length; g++) {
                                                        if (item.valueId == pros[t].values[g].id) {
                                                            if (type == 0) {
                                                                return pros[t].name
                                                            } else {
                                                                if (pros[t].values.length > 1) {
                                                                    return pros[t].values[g].text
                                                                } else {
                                                                    return item.text
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            getTownshipType(t) {
                let str = ''
                this.townshipJson.forEach((item) => {
                    if (item.value == t) {
                        str = item.text || ''
                    }
                })
                return str
            },
            getRegionType(t) {
                let str = ''
                this.regionJson.forEach((item) => {
                    if (item.value == t) {
                        str = item.text || ''
                    }
                })
                return str
            },
            getCondition(t) {
                let str = ''
                this.conditions.forEach((item) => {
                    if (item.value == t) {
                        str = item.text || ''
                    }
                })
                return str
            },
            getWidthAndHeight(e, i) {
                let img = new Image();
                img.src = e.cover
                img.onload = () => {
                    // let str = 'width: ' + img.width + ' ; ' + 'height: ' + img.height + ' ; ' + 'loaded'
                    // console.log(str, 'str')
                    if (img.width > 0 || img.height > 0) {
                        let obj = {
                            wth: null
                        }
                        if (Number(img.width) > Number(img.height)) {
                            obj.wth = 1
                        } else {
                            obj.wth = 0
                        }
                        Object.assign(this.tableData[i], obj)
                    }
                };

            },
            getList(pageNum) {
                if (pageNum == 1) {
                    this.pageData.pageNum = 1;
                    //this.tableData = []; 不能添加这一句
                }
                let searchForm = {};
                searchForm.sort = 'create_datetime desc'
                searchForm.categoryId = this.categoryId
                searchForm.adId = this.id
                searchForm.pageNum = this.pageData.pageNum
                searchForm.pageSize = this.pageData.pageSize
                let params = Qs.stringify(searchForm, {arrayFormat: 'repeat'})
                searchBuyList(params).then((res) => {
                    if (res.data.errorID == 0) {
                        // this.tableData = res.data.object.list || []
                        // wth判断列表图片宽高 start
                        let dataList = res.data.object.list || []
                        for (let i = 0; i < dataList.length; i++) {
                            let obj = {
                                wth: null
                            }
                            Object.assign(dataList[i], obj)
                        }
                        // wth判断列表图片宽高 start
                        // // 刷新列表 or 加载更多
                        if (this.pageData.pageNum == 1) {
                            // this.tableData = res.data.object.list || []
                            this.tableData = dataList

                        } else {
                            // this.tableData = this.tableData.concat(res.data.object.list)
                            this.tableData = this.tableData.concat(dataList)

                        }
                        // // 分页信息配置
                        this.pageInfo.totalPages = res.data.object.pages
                        this.pageInfo.totalCount = res.data.object.total
                        this.pageData.pageNum = this.pageData.pageNum + 1
                        if (this.pageData.pageNum > this.pageInfo.totalPages || this.tableData.length >= this.pageInfo.totalCount) {
                            this.finished = true
                        }
                        // 要求共显示十行：每行两个，总共22个，每次请求十个，最多三次结束请求
                        if (this.pageData.pageNum > 3) {
                            if (this.tableData.length > 22) {
                                this.tableData = this.tableData.slice(0, 22)
                            }
                            this.finished = true
                        }
                        this.loading = false
                    } else {
                        this.$toast(res.data.message)
                        this.finished = true
                        this.loading = false
                    }

                }).catch((e) => {
                    console.log(e)
                    this.$toast('error, please try again later~')
                    this.finished = true
                    this.loading = false
                })
            },
            goToDetail(id) {
                this.$router.push({
                    path: '/buydetail',
                    query: {
                        id: id
                    }
                })
            },
            goToReport() {
                this.$router.push({
                    path: '/user/reportproblem',
                    query: {
                        id: this.adId
                    }
                })
            },
            goToEdit() {
                this.btnLoading = true;
                getUserInfo().then((res) => {
                    if (res.data) {
                        if (res.data.errorID === 0) {
                            this.$router.push({
                                path: '/sell',
                                query: {
                                    goodsId: this.adId
                                }
                            })
                            this.btnLoading = false
                        } else if (res.data.errorID === 100004) {
                            this.$router.push('/login-register/loginregister')
                        } else {
                            this.$toast(res.data.message)
                            this.btnLoading = false
                        }
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        this.$toast('error,please try again leter')
                        this.btnLoading = false
                    })
            },

            getUserId() {
                let userInfo = localStorage.getItem('userInfo') || ''
                if (userInfo) {
                    userInfo = JSON.parse(userInfo);
                    this.userId = userInfo.id;
                }
            },
            onClickSave() {
                if (!this.$store.state.store.isLogin) {
                    this.$router.push('/login-register/loginregister')
                    return false
                } else {
                    let data = {
                        'goodsId': this.id,
                    }
                    let params = Qs.stringify(data)
                    submitSave(params).then((res) => {
                        if (res.data) {
                            // console.log(res.data)
                            if (res.data.errorID == 0) {
                                // this.$toast('success')
                                this.saved = !this.saved
                            } else {
                                this.$toast(res.data.message)
                            }
                        }
                    })
                        .catch((error) => {
                            console.log(error)
                            this.$toast('error,please try again leter')
                        })
                }
            },
            onClickCallBtn(p) {
                if (p) {
                    window.location.href = 'tel:' + p
                }
            },
            Share(param) {
                var name = 'your-name';
                var caption = 'your-caption';
                var description = 'your-description';
                var message = 'share-message';
                var picture = "https://www.tolymoly.com.mm//images/38/06503c826462538f8498160a60f673.jpg";
                var link = "https://www.tolymoly.com.mm/#/help/help";

                window.FB.api('/me/feed', 'post',
                    {
                        caption: caption,
                        name: name,
                        description: description,
                        picture: picture,
                        link: link,
                        message: message,
                        type: "photo"
                    },
                    function (response) {

                    });
            },
        },
        mounted() {
            this.getUserId();

            // 页面跳转进来获取参数
            this.id = this.$route.query.id || ''
            this.myItems = this.$route.query.myItems || ''

            // 调用接口获取详情页面的数据
            this.getDetail(this.id)
            // 调用详情统计
            this.getDetailCount(this.id)
        },
        watch: {
            '$route'(to, from) {
                // console.log(this.$route.query)
                // 路由参数发生变化时
                if (this.$route.query) {
                    // 页面跳转进来获取参数
                    this.id = this.$route.query.id || ''

                    // 调用接口获取详情页面的数据
                    this.getDetail(this.id);
                    // 调用详情统计
                    this.getDetailCount(this.id)
                    window.scrollTo(0, 0);

                    this.finished = true;
                    this.tableData = [];
                    this.pageData.pageNum = 1;
                    this.pageInfo.totalCount = 0;
                    this.pageInfo.totalPages = 0;
                }
            },
        }

    };
</script>
<style>
    .buy-detail .van-cell__left-icon {
        /*margin-left: 16%;*/
        margin-right: 0;
    }

    .buy-detail .van-list__loading {
        width: 100%;
        /*border-top: 1px solid #F2F2F2;*/
    }

    .buy-detail .van-swipe {
        background: #f0f0f0;
        height: 320px;
    }

    .buy-detail .van-swipe .van-swipe-item::before {
        content: 'Tolymoly';
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        text-align: center;
        background: #f0f0f0;
        font-size: 2.5rem;
        font-weight: bold;
        color: #C0BFBF;
        line-height: 320px;
    }

    .edit-btn-box .edit-btn.van-button--large {
        height: 46px;
        line-height: 44px;
    }

    @media (max-width: 375px) and (min-width: 321px) {
        .buy-detail .van-swipe {
            height: 368px;
            line-height: 368px;
        }

        .buy-detail .van-swipe .van-swipe-item::before {
            line-height: 368px;
        }
    }

    @media (max-width: 1080px) and (min-width: 376px) {
        .buy-detail .van-swipe {
            height: 414px;
            line-height: 414px;
        }

        .buy-detail .van-swipe .van-swipe-item::before {
            line-height: 414px;
        }
    }

    .save-btn.saved .van-cell__left-icon {
        color: #DB3743;
    }
</style>
<style scoped>
    .banner-box {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        width: auto;
        height: 100%;
        margin: auto;
    }

    .swiper-banner {
        max-width: 100%;
        max-height: 320px;
        display: block;

        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

    .swiper-banner.no-image {
        background: #f0f0f0;
        font-size: 2.5rem;
        font-weight: bold;
        color: #C0BFBF;
        text-align: center;
    }

    .back-btn {
        position: absolute;
        top: 10px;
        left: 12px;
        width: 34px;
        height: 34px;
        background: rgba(0, 0, 0, .5);
        z-index: 99;
        padding: 9px 8px;
        border-radius: 17px;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }

    .more-btn {
        position: absolute;
        top: 10px;
        right: 12px;
        width: 34px;
        height: 34px;
        background: rgba(0, 0, 0, .5);
        z-index: 99;
        padding: 6px;
        border-radius: 17px;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }

    .more-btn img {
        display: block;
        width: 100%;
        height: 100%;
    }

    .report-btn {
        position: absolute;
        top: 50px;
        right: 0;
        width: 140px;
        /*height: 42px;*/
        line-height: 42px;
        z-index: 99;
        background: #fff;
        padding: 0 10px;
        border: 1px solid #999;
    }

    .container-box {
        padding: 0 4%;
        text-align: left;
    }

    .title {
        margin-top: 3px;
        font-size: 18px;
    }

    .price {
        color: rgb(219, 55, 67);
    }

    .date-time {
        text-align: right;
        color: rgb(161, 161, 161);
    }

    .ft-14 {
        font-size: 14px;
    }

    .margin-b {
        margin-bottom: 14px;
    }

    .detail-items {
        display: flex;
    }

    .item-title {
        color: rgb(161, 161, 161);
    }

    .item-info {
        margin: 0;
        word-wrap: break-word;
    }

    .item-info-categroy {
        width: 100%;
        display: block;
        color: #0E6C9C;
        line-height: 23px;
    }

    .detail-items .item-title {
        flex: 1;
        margin-right: 5px;
    }

    .detail-items .item-info {
        flex: 2;
    }

    .description {
        display: -webkit-box;
        /*! autoprefixer: off */
        -webkit-box-orient: vertical;
        /* autoprefixer: on */
        overflow: hidden;
        line-height: 22px;
    }

    .description.fold {
        -webkit-line-clamp: 4;
    }

    .description.unfold {
        -webkit-line-clamp: 100;
    }

    .more-description {
        color: rgb(14, 108, 156);
        margin-top: 3px;
    }

    .location {
        padding: 15px 4%;
    }

    .cap-title {
        padding: 10px 4%;
        background: rgb(242, 242, 242);
    }

    .user-info-box {
        padding: 15px 0 15px 4%;
        /*border-bottom: 1px solid #F2F2F2;*/

    }

    .user-info {
        position: relative;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        padding-left: 4.1em;
        min-height: 50px;
        line-height: 150%;
        justify-content: space-around;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
        -ms-flex-direction: column;
        flex-direction: column;
    }

    .user-info i {
        position: absolute;
        top: 50%;
        left: 0;
        display: inline-block;
        width: 50px;
        height: 50px;
        margin-top: -25px;
        border-radius: 50%;
        overflow: hidden;
    }

    .user-info p.title {
        font-size: 16px;
        font-weight: 400;
        font-style: normal;
        text-decoration: none;
        padding: 0 4% 0 0;
        margin: 0;
        text-align: left;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }

    .user-info .confirmed {
        margin: 6px 0;
    }

    .user-info .confirmed .confirmed-title {
        color: #a1a1a1;
    }

    .user-info .confirmed .bindphone {
        background: #FF9900;
        border-radius: 50%;
        padding: 5px;
        box-sizing: padding-box;
        display: inline-flex;
        height: 100%;
        margin-right: 7px;
    }

    .user-info .confirmed .bindfacebook {
        background: #0E6C9C;
        border-radius: 50%;
        padding: 5px;
        box-sizing: padding-box;
        display: inline-flex;
        height: 100%;
        margin-right: 7px;
    }

    .user-info .confirmed img {
        height: 14px;
    }

    .user-info i img {
        width: 100%;
        display: block;
    }

    .face-icon-box {
        height: 24px;
    }

    .face-icon-box img {
        display: inline-block;
        height: 24px;
        width: auto;
    }

    .face-icon {
        display: inline-flex;
        height: 100%;
        margin-right: 6px;
    }

    .save {
        -webkit-box-flex: 1;
        -ms-flex: 1;
        flex: 1;
    }

    .save-btn {
        padding: 13px 15px !important;
        text-align: center;
        font-size: 16px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .chat-btn {
        background: #FF9A03;
    }

    .buy-btn {
        background: #DB3743;
    }

    .main-explore {
        padding: 0;
        margin: 0;
        margin-bottom: 14px;
    }

    .main-explore {
        position: relative;
        background: #fff;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        text-align: center;
        flex-wrap: wrap;
        margin-top: 8px;
        padding-right: 4%;
    }

    .main-explore .explore-item {
        display: block;
        padding: 14px 0 0;
        margin-left: 4%;
        width: 46%;
        text-decoration: none;
        color: #000;
        /*margin-right: 8%;*/
        /*border-bottom: 1px solid #F2F2F2;*/
    }

    .main-explore .explore-item.one:nth-last-child(2), .main-explore .explore-item.two:nth-last-child(2) {
        border-bottom: none;
    }

    .main-explore .explore-item.two:nth-last-child(3) {
        border-bottom: none;
    }

    .main-explore .explore-item:nth-child(2n) {
        margin-right: 0;
    }

    .main-explore .explore-item .explore-item-icon {
        width: 100%;
        /*height: 135px;*/
        /*margin: 0 auto 5px;*/
        /*border: 1px solid #eee;*/
        align-items: center;
        display: flex;
        background: #f0f0f0;
        position: relative;
        z-index: 0;
        height: 0;
        padding: 0 0 100%;
        overflow: hidden;
        border-radius: 6px;
    }

    .main-explore .explore-item .explore-item-icon::before {
        content: "Tolymoly";
        position: absolute;
        top: 50%;
        bottom: 0;
        right: 0;
        left: 0;
        text-align: center;
        background: #f0f0f0;
        font-size: 1.5rem;
        font-weight: 700;
        color: #c0bfbf;
        /*line-height: 135px;*/
        z-index: -1;
        margin-top: -12px;
    }

    .main-explore .explore-item > * {
        display: block;
        margin: 0 auto;
    }

    .main-explore .explore-item-icon img {
        /*max-width:100%;*/
        /*max-height:100%;*/
        /*display: block;*/
        /*margin: 0 auto;*/
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 1;
        width: 100%;
    }

    .main-explore .explore-item-icon img.width-max {
        width: auto;
        left: 50%;
        right: auto;
        height: 100%;
        transform: translate(-50%);
    }

    .main-explore .explore-item-icon img.height-max {
        top: 50%;
        transform: translateY(-50%);
    }

    .main-explore .explore-item .explore-item-label {
        /*color: inherit;*/
        font-size: 14px;
        line-height: 160%;
        margin-top: 4px;
        text-align: left;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;

        /*font-size: 12px;*/
        /*font-family: Bitter,sans-serif;*/
        color: #000;
    }

    .main-explore .explore-item .explore-item-label.price {
        /*color: #DB3743;*/
        /*font-size: 16px;*/
        /*font-weight: 600;*/
        font-size: 14px;
        color: #4c4c4c;
    }

    .main-explore .explore-item .explore-item-label.dates {
        color: #A1A1A1;
    }

    /*.shopgogo::before{*/
    /*content: 'shopgogo';*/
    /*position: absolute;*/
    /*top: 0;*/
    /*bottom: 0;*/
    /*right: 0;*/
    /*left: 0;*/
    /*text-align: center;*/
    /*z-index: -1;*/
    /*background: #f0f0f0;*/
    /*font-size: 2.5rem;*/
    /*font-weight: bold;*/
    /*color: #C0BFBF;*/
    /*line-height: 320px;*/
    /*}*/
    .loading-page {
        position: absolute;
        top: 50%;
        margin-top: -10px;
        left: 50%;
        margin-left: -15px;
    }

    .edit-btn-box {
        position: fixed;
        width: 100%;
        padding: 5px 0;
        bottom: 0;
        left: 0;
        background: #fff;
        z-index: 9;
    }

    .edit-btn-box .edit-btn {
        border: 1px solid #f90;
        background: #f90;
        border-radius: 5px;
        color: #fff;
        width: 92%;
        margin: 0 4%;
    }

    .van-cell-text {
        color: #0e6c9c;
    }

    @media (max-width: 375px) and (min-width: 321px) {
        .swiper-banner {
            max-height: 368px;
            line-height: 368px;
        }

        .main-explore .explore-item .explore-item-icon {
            /*height: 155px;*/
        }

        .main-explore .explore-item .explore-item-icon::before {
            /*line-height: 155px;*/
        }

        .face-icon {
            margin-right: 15px;
        }

        .shopgogo::before {
            line-height: 368px;
        }
    }

    @media (max-width: 1080px) and (min-width: 376px) {
        .swiper-banner {
            max-height: 414px;
            line-height: 414px;
        }

        .main-explore .explore-item .explore-item-icon {
            /*height: 173px;*/
        }

        .main-explore .explore-item .explore-item-icon::before {
            /*line-height: 173px;*/
        }

        .face-icon {
            margin-right: 15px;
        }

        .shopgogo::before {
            line-height: 414px;
        }
    }
</style>
